package echoTCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class MyTcpEchoClient {

    Socket clientSocket = null;


    // 进行连接
    public MyTcpEchoClient(String ip , int port) {
        try {
            // 进行连接
            clientSocket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public  void start() {
        // 开始交互
            System.out.println("客户端开始运行...");


                // 发送请求并接受响应
                ProcessServerConnect(clientSocket);




    }

    private void ProcessServerConnect(Socket socket) {
        try(InputStream inputSTream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()
        ) {

            while(true) {

                Scanner in = new Scanner(System.in);
                System.out.print("请输入你的需求-> ");


//                输入请求并发送
                String request = in.nextLine();

                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                // 进行刷新
                printWriter.flush();


                // 接收响应并输出
                Scanner scanner = new Scanner(inputSTream);
                if(!scanner.hasNext()) {
                    break;
                }

                String response = scanner.nextLine();

                System.out.println("response = "+ response);



            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.printf("任务执行结束： [%s,%d]\n",socket.getInetAddress(),socket.getPort());
            try {
//                    关闭 socket 流
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }


    public static void main(String[] args) {
        MyTcpEchoClient myTcpEchoClient = new MyTcpEchoClient("127.0.0.1",9090);
        myTcpEchoClient.start();
    }
}
